package com.example.core.convert.form;

import com.example.core.convert.utils.ConvertorUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import javax.persistence.EntityManager;
import java.lang.reflect.Field;

@Data
public class FormConvertor_IDToModel implements FormConvertor {

    Logger logger = LoggerFactory.getLogger(getClass());
    private String property;
    private Class<?> clazz;

    public FormConvertor_IDToModel(String property, Class<?> clazz) {
        this.property = property;
        this.clazz = clazz;
    }

    @Override
    public void convertor(Object model, Object val) throws Exception {
        EntityManager entityManager = ConvertorUtils.getInstance().getEntityManager();
        if (val != null && val instanceof String) {
            String id = (String) val;
            Object obj = entityManager.find(this.clazz, id);
            Field field = ReflectionUtils.findField(model.getClass(), property);
            field.setAccessible(true);
            field.set(model, obj);
        }
    }
}
